package com.java.design.spring.beans.factory.xml;

import com.java.design.spring.beans.BeanDefinition;
import com.java.design.spring.beans.MuTablePropertyValues;
import com.java.design.spring.beans.PropertyValue;
import com.java.design.spring.beans.factory.support.BeanDefinitionReader;
import com.java.design.spring.beans.factory.support.BeanDefinitionRegistry;
import com.java.design.spring.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author dgg
 * @date 2023/3/28 22:30
 * @description: 针对xml文件进行解析
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    //声明注册表对象
    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        registry = new SimpleBeanDefinitionRegistry();


    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        SAXReader reader = new SAXReader();
        //获取类路径下文件
        InputStream resourceAsStream = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        Document read = reader.read(resourceAsStream);

        //根据document对象获取跟标签对象
        Element rootElement = read.getRootElement();

        //获取标签下的所有bean标签
        List bean = rootElement.elements("bean");

        for (Object element : bean) {
            Element e = (Element) element;
            //获取id属性
            String id = e.attributeValue("id");
            //获取class
            String className = e.attributeValue("class");

            //封装到BeanDefinition对象中

            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);

            //获取bean标签下所有的property标签对象
            List property = e.elements("property");
            MuTablePropertyValues muTablePropertyValues = new MuTablePropertyValues();
            for (Object o : property) {
                Element pe = (Element) o;
                String name = pe.attributeValue("name");
                String ref = pe.attributeValue("ref");
                String value = pe.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name, ref, value);
                muTablePropertyValues.add(propertyValue);
            }
            //将MuTablePropertyValues封装到beanDefinition
            beanDefinition.setPropertyValues(muTablePropertyValues);
            //将 beanDefinition 注册到 SimpleBeanDefinitionRegistry
            registry.registerBeanDefinition(id, beanDefinition);
        }
    }
}
